import React, { Component } from 'react';
import Buttonbar from './Buttonbar';
import './scss/Noticedetails.scss';
// import Header from '../../common/compont/Header';
import Header from './header/Header';
// import Navigation from './Navigation';
import Footer from '../../common/compont/Footer';
import { Spin, message } from 'antd';
import { LgButton } from 'lancoo-web-ui';
import { postData, getData } from '../../common/js/fetch';
import Base64 from '../../common/js/fetch/base64';
import Alert from '../../common/compont/alert_dialog_wrapper';
import { createHashHistory } from 'history';
import { Scrollbars } from 'react-custom-scrollbars';

class Noticedetails extends Component {
    constructor(props) {
        super(props);
        console.log(props, 'detail');
        this.state = {
            message: {},
            data: [],
            editState: 0, //编辑状态，0表示查看，1表示编辑
            loading: true,
            headerName: '新闻资讯',
            UserID: sessionStorage.getItem('UserID') ? sessionStorage.getItem('UserID') : '',
            UserType: sessionStorage.getItem('UserType') ? sessionStorage.getItem('UserType') : '',
            UserClass: sessionStorage.getItem('UserClass') ? sessionStorage.getItem('UserClass') : '',
            changeTabFlag: false,
            newsAttachmentVoList: [],
            systemInfo: JSON.parse(sessionStorage.getItem('systemInfo')),
        };
    }
    getQueryVariable(variable) {
        var query = window.location.hash.substring(1).split("?");
        query = query[1];
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] === variable) { return pair[1]; }
        }
        return (false);
    }
    showhtml(htmlString) {
        var html = { __html: htmlString };
        return <div dangerouslySetInnerHTML={html}></div>;
    }
    componentDidMount() {
        let token = this.getQueryVariable('lg_tk');
        let NoticeID = this.getQueryVariable('newsId');
        let UserID = this.getQueryVariable('UserID')
        if (!token) {
            token = sessionStorage.getItem('token');
        }
        let {
            systemInfo
        } = this.state
        //表示发送新闻公告
        // if (window.location.href.split('?')[0].indexOf('RecNewsContent') == -1 || (UserID != sessionStorage.getItem('UserID') && sessionStorage.getItem('UserID') == "0")) {
        if (window.location.href.split('?')[0].indexOf('RecNewsContent') == -1 ) {

            // console.log("debug 信息:", window.location.href, sessionStorage.getItem('UserType'))
            // console.log(sessionStorage.getItem('UserType') !== '0')
            // if (sessionStorage.getItem('UserType') !== '0') {
            //     const history = createHashHistory();
            //     // history.push('/Error');
            //     return
            // }
            getData('api/news/info/detailed', {
                // UserID: sessionStorage.getItem('UserID'),
                newsId: NoticeID,
                // UserType: sessionStorage.getItem('UserType')
            }).then(res => {
                return res.json()
            }).then(json => {
                // console.log(json);
                if (json.code == 200) {
                    if (!json.data) {
                        const history = createHashHistory();
                        // history.push('/Error');
                        return
                    }
                    let Data = json.data;
                    if (Data.beEduPush == '1') {
                        Data.newsAttachmentVoList && Data.newsAttachmentVoList.forEach(item => {
                            item.attachmentUrl = systemInfo.governmentWebUrl + '/' + item.attachmentUrl
                            console.log(item.attachmentUrl, 'item.attachmentUrl');
                        })
                    }
                    this.setState({
                        data: Data,
                        newsAttachmentVoList: Data.newsAttachmentVoList,
                    })
                    console.log(Data);
                    if (Data.userId == sessionStorage.getItem('UserID') || (this.state.UserType == '0' && (this.state.UserClass == '2' || this.state.UserClass == '4'))) {
                        this.setState({
                            editState: 1,
                        }, () => {
                            this.setState({
                                loading: false
                            })
                        })
                    } else {
                        this.setState({
                            loading: false
                        })
                    }
                } else {
                    this.setState({
                        changeTabFlag: true
                    })

                }

            })
        }
        //表示查看新闻公告
        else {
            console.log("debug 信息2:", window.location.href)
            getData('api/news/info/detailed', {
                // UserID: sessionStorage.getItem('UserID') ? sessionStorage.getItem('UserID') : '',
                newsId: NoticeID,
                // Sign: '0',
            }).then(res => {
                return res.json()
            }).then(json => {
                // console.log(json);
                if (json.code == 200 && json.data) {
                    let Data = json.data;
                    if (Data.beEduPush == '1') {
                        Data.newsAttachmentVoList && Data.newsAttachmentVoList.forEach(item => {
                            item.attachmentUrl = systemInfo.governmentWebUrl + '/' + item.attachmentUrl
                            console.log(item.attachmentUrl, 'item.attachmentUrl');
                        })
                    }
                    this.setState({
                        data: Data,
                        state: 0,
                        newsAttachmentVoList: Data.newsAttachmentVoList,
                    }, () => {
                        this.setState({
                            loading: false
                        })
                        if (window.opener) {
                            window.opener.postMessage('11', '*');
                        }
                    })
                } else {
                    this.setState({
                        changeTabFlag: true
                    })

                }
            })
        }


    }

    toErrorPage() {
        const history = createHashHistory();
        history.push('/Error');
        return
    };


    downFile(url, name) {
        let data = this.state.data
        message.config({
            top: 50,
        })
        const hide = message.loading('正在下载，请稍等..', 0);
        var x = new XMLHttpRequest();
        // let url1 = sessionStorage.getItem('itemUrl') + url;
        console.log(url, 'url1');
        x.open("GET", url, true);
        x.responseType = 'blob';
        x.onload = function (e) {
            hide()
            var url = window.URL.createObjectURL(x.response);
            var a = document.createElement('a');
            a.href = url;
            a.download = name;
            a.click();
            URL.revokeObjectURL(url);
        }
        x.send();
    };
    changeTab(data) {
        if (data) {
            window.opener = null;
            window.open('', '_self');
            window.close();
        }
    }

    preViewFile = (item) => {
        console.log(item)
        let schoolId = sessionStorage.getItem('schoolId')
        // // let filePath = '';
        // if (item.attachmentUrl.indexOf('http://') > -1 || item.attachmentUrl.indexOf('https://') > -1) {
        //     filePath = item.attachmentUrl;
        // } else {
        //     filePath = sessionStorage.getItem('itemUrl') + '/' + item.attachmentUrl;
        // }
        // filePath = filePath.replace(/[\\]+/g, '/');
        // let base64 = new Base64();
        // let url = encodeURIComponent(base64.encode(filePath));
        // let webSvrAddr = JSON.parse(sessionStorage.getItem('preview'))[0].webSvrAddr
        // console.log(JSON.parse(sessionStorage.getItem('preview'))[0].webSvrAddr)
        // console.log(url)
        // window.open(`${webSvrAddr}onlinePreview/?url=${url}&eduId=${schoolId}`);
        // console.log(filePath)
        // window.open(filePath);
        let filePath = '';
        let previewSystem = JSON.parse(sessionStorage.getItem('preview'))
        console.log(previewSystem)
        if (item.attachmentUrl.indexOf('http://') > -1 || item.attachmentUrl.indexOf('https://') > -1) {
            filePath = item.attachmentUrl;
        } else {
            filePath = sessionStorage.getItem('itemUrl') + '/' + item.attachmentUrl;
        }
        filePath = filePath.replace(/[\\]+/g, '/');
        let base64 = new Base64();
        let url = encodeURIComponent(base64.encode(filePath));
        let webSvrAddr = previewSystem[0].webSvrAddr;
        window.open(`${webSvrAddr}onlinePreview?url=${url}&eduId=${schoolId}`);
    }
    render() {
        console.log("是否可编辑：", this.state.editState == 1)
        let {
            newsAttachmentVoList,
            systemInfo,
            data
        } = this.state

        return (
            <div>
                <Alert
                    noCancel={true}
                    isConfirm={true}
                    className="sendAgain-alert"
                    message="新闻已被撤回"
                    isOpen={this.state.changeTabFlag}
                    chooseFn={(data) => { this.changeTab(data) }}>
                </Alert>
                <div>
                    <Header headerStyle={3} headerName={this.state.headerName} detailed={1}></Header>
                    {this.state.loading ?
                        <Spin size="large" /> :
                        data.beEduPush != '1' && (this.state.data.userId === this.state.UserID ||
                            (this.state.UserType == '0' && this.state.UserClass == '2')) ?
                            this.state.editState === 1 ?
                                <Buttonbar message1="撤回" color='blue' color2='red' NoticeID={this.state.data.newsId} NoticeName={this.state.data}></Buttonbar> :
                                // <Buttonbar message1="撤回" color='blue' message2="删除" color2='red' NoticeID={this.state.data.newsId}></Buttonbar> :
                                '' :
                            ''}
                    {this.state.data ? <div className='notice-details-all'>
                        <div className='notice-details-middle'>
                            <h1>{this.state.data.newsTitle}</h1>
                            {/* {this.state.editState === 1 ? <p className='notice-details-message'><span><b> 发布者: </b>{this.state.data.userName} </span>
                                <span style={{ color: '#999999' }}> <b>发布时间: </b>{this.state.data.releaseTime}</span>
                                <span><b> 阅读次数:  </b>{this.state.data.readCount ? this.state.data.readCount : '0'}次</span></p>
                                : <p className='notice-details-message'><span > <b>发布时间: </b>{this.state.data.releaseTime}</span>
                                    <span><b> 类别: </b>{this.state.data.newsTypeName} </span><span><b> 阅读次数:  </b>{this.state.data.readCount ? this.state.data.readCount : '0'}次</span></p>} */}
                            <p className='notice-details-message'><span > <b>发布时间: </b>{this.state.data.releaseTime}</span>
                                <span><b> 类别: </b>{this.state.data.newsTypeName} </span><span><b> 阅读次数:  </b>{this.state.data.readCount ? Number(this.state.data.readCount) + 1 : '0'}次</span></p>
                            <div className="notice-content notice-contect">{this.showhtml(this.state.data.newsContent)}</div>
                            {newsAttachmentVoList.length > 0 ? <div className="notice-down-box" style={{ height: newsAttachmentVoList.length > 1 ? '238px' : '' }}>
                                <p><i ></i>附件下载</p>
                                <Scrollbars autoHeight autoHeightMax={180} autoHide autoHideTimeout={100}>
                                    {
                                        newsAttachmentVoList.map(item => {
                                            return (
                                                <div className="notice-down-message">
                                                    <span className={item.attachmentName.slice(item.attachmentName.lastIndexOf('.') + 1, item.attachmentName.length) + ' uploadType-img'}></span>
                                                    <p onClick={() => { this.preViewFile(item) }} style={{ cursor: 'pointer' }} title={item.attachmentName.length > 60 ? item.attachmentName : ''}>{item.attachmentName.length > 60 ? item.attachmentName.slice(0, 58) + '..' : item.attachmentName}
                                                        <span>{(item.attachmentSize / 1024 / 1024) >= 1 ? '[' + (item.attachmentSize / 1024 / 1024).toFixed(1) + 'MB]' : '[' + (item.attachmentSize / 1024).toFixed(1) + 'KB]'}</span></p>
                                                    <LgButton onClick={() => { this.preViewFile(item) }} textUnderline type='info' shapeType='text' className='preview-file'>预览</LgButton>
                                                    <b className='down-file' href={item.attachmentUrl.indexOf('.mp4') === -1 && item.attachmentUrl.indexOf('.mp4') === -1 ? item.attachmentUrl : item.attachmentUrl + '?filename=' + item.attachmentName.slice(0, -4)} download={item.attachmentName} onClick={() => { this.downFile(item.attachmentUrl, item.attachmentName); }}>下载</b>
                                                </div>
                                            )
                                        })
                                    }
                                </Scrollbars>

                            </div> : ''}
                        </div>
                    </div> : <div></div>}
                    {/* <Footer></Footer> */}
                </div>
            </div>
        )

    }

}

export default Noticedetails;